import { BlockEnum, NodeProps } from '@/components/workflow/types'
import { useWorkFlowStore } from '@/store/workflowStore'
import type { FC } from 'react'
import React, { useEffect, useState, useCallback } from 'react'
import { ComponentDescMap } from '../../constants'
import '../style.less'
import { getIterationDefaultParams } from './default'
import { Background, Handle, Position, useViewport, useReactFlow, useOnSelectionChange } from 'reactflow';

const IterationNode: FC<NodeProps> = ({ id, data }: any) => {
  const { flowVariables } = useWorkFlowStore()
  const [info, setInfo] = useState({ ...getIterationDefaultParams() })
  const { zoom } = useViewport()
  const { getNodes, setNodes } = useReactFlow()
  const childNodes = getNodes().filter(node => node.parentId === id) || []
  const minWidth = 600
  const minHeight = 300
  
  const [subflowSize, setSubflowSize] = useState({ width: minWidth, height: minHeight })
  
  // 更新子流程区域尺寸
  const updateSubflowSize = useCallback(() => {
    if (childNodes.length === 0) {
      setSubflowSize({ width: minWidth, height: minHeight })
      return
    }
    
    const padding = 0
    let maxX = -Infinity
    let maxY = -Infinity
    
    childNodes.forEach(node => {
      const nodeWidth = node.width || 150  // 默认节点宽度
      const nodeHeight = node.height || 40  // 默认节点高度
      const rightEdge = node.position.x + nodeWidth
      const bottomEdge = node.position.y + nodeHeight
      
      maxX = Math.max(maxX, rightEdge)
      maxY = Math.max(maxY, bottomEdge)
    })
    
    setSubflowSize({
      width: Math.max(minWidth, maxX + padding),
      height: Math.max(minHeight, maxY + padding)
    })
  }, [childNodes, minWidth, minHeight])

  // 监听子节点变化
  useEffect(() => {
    updateSubflowSize()
  }, [childNodes])

  useOnSelectionChange({
    onChange: ({ nodes }) => {
      nodes.forEach(node => {
        if(node.parentId === id) {
          updateSubflowSize()
        }
      })
    }
  })

  return (
    <div className="workflow-common-node iteration-node" data-id={id} style={{
        width: subflowSize.width,
        height: subflowSize.height - 40
      }}>
        <div className="common-node-desc">{data.desc || ComponentDescMap[BlockEnum.Iteration]}</div>
        <div 
          className="iteration-subflow pl-2 border-[1px] border-gray-100 rounded-[8px] bg-gray-50" 
          style={{ 
            width: subflowSize.width - 20,
            height: subflowSize.height - 80,
            position: 'relative',
            margin: '10px',
            zIndex: 0
          }}
        >
          <div style={{ position: 'absolute', inset: 0 }}>
            <Background
              color="#ccc"
              className='!z-0 rounded-xl'
              gap={[14 / zoom, 14 / zoom]}
              size={2 / zoom}
            />
          </div>
        </div>
      </div>
    )
}

export default React.memo(IterationNode)